<?php
namespace Common\Model;
use Common\Model\BaseModel;
/**
 * 菜单操作model
 */
class LinksModel extends BaseModel{

    // 自动验证
    protected $_validate=array(
        array('name','require','名称不能为空',0,'',3), // 验证字段必填
        array('name','require','链接不能为空',0,'',3), // 验证字段必填
    );

    // 自动完成
    protected $_auto=array(
        array('create_time','time',1,'function'), // 对date字段在新增的时候写入当前时间戳
    );


    public function getAdminList($param){
        $keyword = $param['keyword'];
        if (!empty($keyword)) {
            $map['name'] = array('like','%'.$keyword.'%');
        }
        $assign = $this->getAdminPage($this,$map,$param,'id desc');
        return $assign;
    }


	/**
     * 添加友情链接
     */
    public function addData($data){
        // 对data数据进行验证
        if(!$data=$this->create($data)){
            // 验证不通过返回错误
            return false;
        }else{
            // 验证通过
            $data['content']=htmlspecialchars_decode($data['content']);
            $data['content']=preg_replace('/src=\"^\/.*\/Upload\/image\/ueditor$/','src="/Upload/image/ueditor',$data['content']);
            $data['content']=htmlspecialchars($data['content']);
            $result=$this->add($data);
            return $result;
        }
    }

    /**
     * 修改友情链接
     */
    public function editData($map,$data){
        // 对data数据进行验证
        if(!$data=$this->create($data)){
            // 验证不通过返回错误
            return false;
        }else{
            //如果上传了新logo，删除旧的logo
            $logo = $this->where($map)->getField('logo');
            if ($logo != $data['logo']) {
                deleteFile($logo);
            }
            $data['content']=htmlspecialchars_decode($data['content']);
            $data['content']=preg_replace('/src=\"^\/.*\/Upload\/image\/ueditor$/','src="/Upload/image/ueditor',$data['content']);
            $data['content']=htmlspecialchars($data['content']);
            // 验证通过
            $result=$this
                ->where(array($map))
                ->save($data);
            return $result;
        }
    }

    //获取友情链接详情
    public function getData($map){
        $data = $this->where($map)->find();
        $data['content']=htmlspecialchars_decode($data['content']);
        $data['content']=preg_replace('/src=\"^\/.*\/Upload\/image\/ueditor$/','src="/Upload/image/ueditor',$data['content']);
        return $data;
    }
    
    /**
     * 删除数据
     * @param   array   $map    where语句数组形式
     * @return  boolean         操作是否成功
     */
    public function deleteData($map){
        $logo = $this->where($map)->getField('logo');
        $result = $this->where($map)->delete();
        if($result){
            deleteFile($logo);
            return true;
        }else{
            return false;
        }
    }

}
